// 引用使用es6的module引入和定义
// 全局变量以g_开头
// 私有函数以_开头
import { Config } from './config.js';
import { Base } from './base.js';

class Token {
    constructor() {
        this.verifyUrl = Config.resUrl + 'user/verifyToken';
        this.tokenUrl = Config.resUrl + 'user/getToken';
        this.b = new Base();
    } //验证token

    verify() {
        var token = uni.getStorageSync('token');

        if (!token) {
            this.getTokenFromServer();
        } else {
            this._verifyFromServer(token);
        }
    } //获取token

    getTokenFromServer(callback) {
        var that = this;
        uni.login({
            success: function (res) {
                var data = {};
                var userInfo = getApp().globalData.userInfo;

                if (userInfo) {
                    data = userInfo;
                }

                data.code = res.code;
                that.b.apiRequest(
                    {
                        url: 'user/getToken',
                        type: 'post',
                        data: data
                    },
                    (o) => {
                        if (o.code == 1) {
                            uni.setStorageSync('token', o.data.token);
                            uni.setStorageSync('userinfo', o.data.userinfo);
                            callback && callback(o.data);
                        } else {
                            uni.setStorageSync('userinfo', '');
                            uni.setStorageSync('token', '');
                            uni.navigateTo({
                                url: '/pages/login/login'
                            });
                        }
                    }
                );
            }
        });
    } //携带令牌到服务器校验

    _verifyFromServer(token) {
        var that = this;
        uni.request({
            url: this.verifyUrl,
            method: 'POST',
            data: {
                token: token
            },
            success: function (res) {
                var valid = res.data.data;

                if (!valid) {
                    that.getTokenFromServer();
                }
            }
        });
    }
}

export { Token };
